﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zj.OpenAuth.Domain.Core;
using Zj.OpenAuth.Domain.Interface;
using Zj.OpenAuth.DTO.Common;

namespace Zj.OpenAuth.App.MenuApp
{
    /// <summary>
    /// menu application service  implement
    /// </summary>
    public class MenuAppService : IMenuAppService
    {
        public readonly IMenuRepository _repository;
        public MenuAppService(IMenuRepository repository)
        {
            this._repository = repository;
        }


        /// <summary>
        /// add or edit department 
        /// </summary>
        /// <returns></returns>
        public bool AddOrEdit(MenuDTO dto)
        {
            Menu menu= Mapper.Map<MenuDTO, Menu>(dto);
            if (dto.Id!=0&&Get(menu.Id) != null)
            {
                menu = _repository.Get(menu.Id);
                menu.Text = dto.Text;
                menu.MenuType = dto.MenuType;
                menu.Code = dto.Code;
                menu.Url = dto.Url;
                menu.Description = dto.Description;
                menu.Icon = dto.Icon;

                menu.LastModifyTime = DateTime.Now;

                menu = _repository.Update(menu);
            }
            else
            {
                var rt = _repository.Query(m => m.ParentId == menu.ParentId);
                if (rt==null||rt.Count()<=0)
                {
                    menu.Sort = 0;
                }
                else
                {
                    menu.Sort = rt.Max(m=>m.Sort)+1;
                }

                menu = _repository.Insert(menu);
            }
            return menu == null ? false : true;
        }



        /// <summary>
        /// delete department
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public void Delete(int id)
        {
            _repository.Delete(id);
        }


        public void DeleteMuti(List<int> ids)
        {
            ids.ForEach(id => _repository.Delete(id));
        }

        public MenuDTO Get(int id)
        {
            return Mapper.Map<Menu, MenuDTO>(_repository.Get(id));
        }


        public List<MenuDTO> GetAllList()
        {
            return Mapper.Map<List<Menu>, List<MenuDTO>>(_repository.Query(s => s.Status != StatusEnum.Deleted).ToList());
        }

        public List<MenuDTO> GetChildrenByParent(int? id, int pageIndex, out int rowCount, int pageSize = 10)
        {
            return Mapper.Map<List<Menu>, List<MenuDTO>>(
                _repository.QueryPage(s => s.Status != StatusEnum.Deleted && s.ParentId == id.Value, pageSize, pageIndex, out rowCount, s => s.Id)
                .ToList());
        }
    }
}
